<template>
  <div class="main">
    <div class="header">
      <h2>权限管理</h2>
    </div>

    <!-- 搜索表单 -->
    <div class="search-container">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
              v-model="searchParams.name"
              placeholder="请输入权限名称"
              clearable
              prefix-icon="Search"
              @keyup.enter="search"
          >
          </el-input>
        </el-col>
        <el-col :span="16">
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="success" :icon="Plus" @click="add">添加权限</el-button>
          <el-button type="danger" :icon="Delete" @click="deleteRows">批量删除</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 表格展示区域 -->
    <div class="data-container">
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          :header-cell-style="{ textAlign: 'center', backgroundColor: '#f5f7fa' }"
          :cell-style="{ textAlign: 'center' }"
          ref="tableRef"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="name" label="权限名称" width="150" />
        <el-table-column prop="description" label="权限描述" min-width="200">
          <template #default="scope">
            <div class="description-cell" @click="showFullDescription(scope.row.description)">
              {{ truncateText(scope.row.description, 50) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.enabled ? 'success' : 'danger'">
              {{ scope.row.enabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdBy" label="创建人" width="120" />
        <el-table-column prop="createdTime" label="创建时间" width="160" />
        <el-table-column prop="updatedBy" label="更新人" width="120" />
        <el-table-column prop="updatedTime" label="更新时间" width="160" />
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" :icon="Edit" @click="editRow(scope.row)" size="small">
              编辑
            </el-button>
            <el-button type="danger" :icon="Delete" @click="deleteRow(scope.row)" size="small">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pagination.pageNo"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
        v-model="showDialog"
        :title="title"
        width="500px"
        :before-close="handleDialogClose"
    >
      <el-form :model="perm" ref="formRef" label-position="right" label-width="100px">
        <el-form-item label="权限名称:" prop="name" required>
          <el-input placeholder="请输入权限名称" v-model="perm.name" />
        </el-form-item>
        <el-form-item label="权限描述:" prop="description">
          <el-input
              type="textarea"
              placeholder="请输入权限描述"
              v-model="perm.description"
              :rows="4"
          />
        </el-form-item>
        <el-form-item label="状态:" prop="enabled">
          <el-switch
              v-model="perm.enabled"
              active-text="启用"
              inactive-text="禁用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限描述详情弹窗 -->
    <el-dialog
        v-model="showDescriptionDialog"
        title="权限描述详情"
        width="500px"
    >
      <div class="description-content">
        {{ currentDescription }}
      </div>
      <template #footer>
        <el-button type="primary" @click="showDescriptionDialog = false">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Plus, Edit, Search, Delete } from '@element-plus/icons-vue'
import { ref, onMounted, toRaw, nextTick } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { findAll, deleteById, save, update, deleteAll } from '@/api/PermApi'

onMounted(() => {
  search()
})

const tableData = ref([])
const pagination = ref({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

const searchParams = ref({
  name: "",
})

const showDialog = ref(false)
const showDescriptionDialog = ref(false)
const currentDescription = ref('')
const title = ref("新增权限")

const perm = ref({
  id: null,
  name: "",
  description: "",
  enabled: true,
  createdBy: "",
  updatedBy: "",
  createdTime: "",
  updatedTime: ""
})

const formRef = ref()
const tableRef = ref()

async function search() {
  try {
    let resp = await findAll(pagination.value.pageNo, pagination.value.pageSize, searchParams.value)
    tableData.value = resp.records
    pagination.value.total = resp.total
  } catch (error) {
    ElMessage.error('获取权限列表失败')
  }
}

function deleteRow(row) {
  let id = row.id
  deletePerm(id)
}

function deletePerm(id) {
  ElMessageBox.confirm("是否确认删除该权限?", "警告", {
    type: "warning",
  })
      .then(async () => {
        let resp = await deleteById(id)
        if (resp.code == 200) {
          ElMessage.success(resp.msg || "删除成功")
          search()
        } else {
          ElMessage.error(resp.msg || "删除失败")
        }
      })
      .catch(() => { })
}

function deleteRows() {
  let rows = tableRef.value.getSelectionRows()
  let ids = []
  for (let row of rows) {
    ids.push(toRaw(row).id)
  }
  deleteAllRows(ids)
}

async function deleteAllRows(ids) {
  if (ids.length == 0) {
    ElMessage.warning("请选择想要删除的行")
  } else {
    ElMessageBox.confirm("是否确认删除所选权限?", "警告", {
      type: "warning",
    })
        .then(async () => {
          let resp = await deleteAll(ids)
          if (resp.code == 200) {
            ElMessage.success(resp.msg || "删除成功")
            search()
          } else {
            ElMessage.error(resp.msg || "删除失败")
          }
        })
        .catch(() => { })
  }
}

function add() {
  showDialog.value = true
  title.value = "新增权限"
  perm.value = {
    id: null,
    name: "",
    description: "",
    enabled: true,
    createdBy: "",
    updatedBy: "",
    createdTime: "",
    updatedTime: ""
  }
}

function submitForm() {
  let permData = toRaw(perm.value)
  if (permData.id) {
    updatePerm(permData)
  } else {
    addPerm(permData)
  }
}

async function addPerm(permData) {
  try {
    let resp = await save(permData)
    if (resp.code == 200) {
      ElMessage.success("添加成功")
      search()
      showDialog.value = false
    } else {
      ElMessage.error(resp.msg || "添加失败")
    }
  } catch (error) {
    ElMessage.error("添加失败")
  }
}

function editRow(row) {
  showDialog.value = true
  title.value = "编辑权限"
  nextTick(() => {
    perm.value = { ...row }
  })
}

async function updatePerm(permData) {
  try {
    let resp = await update(permData)
    if (resp.code == 200) {
      ElMessage.success("修改成功")
      search()
      showDialog.value = false
    } else {
      ElMessage.error(resp.msg || "修改失败")
    }
  } catch (error) {
    ElMessage.error("修改失败")
  }
}

function handleSizeChange(val) {
  pagination.value.pageSize = val
  search()
}

function handleCurrentChange(val) {
  pagination.value.pageNo = val
  search()
}

function handleDialogClose(done) {
  ElMessageBox.confirm('确认关闭？')
      .then(() => {
        done()
      })
      .catch(() => {})
}

function truncateText(text, length) {
  if (!text) return ''
  return text.length > length ? text.substring(0, length) + '...' : text
}

function showFullDescription(description) {
  currentDescription.value = description
  showDescriptionDialog.value = true
}
</script>

<style scoped>
.main {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  font-size: 24px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.search-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.data-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.description-cell {
  cursor: pointer;
  color: #409eff;
  text-decoration: underline;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.description-content {
  white-space: pre-wrap;
  line-height: 1.6;
  color: #606266;
}

.dialog-footer {
  padding: 0 20px 20px;
  text-align: right;
}
</style>